package com.stylefeng.guns.modular.fileManage.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.dao.ZyPictureMapper;
import com.stylefeng.guns.common.persistence.dao.ZyTeaMapper;
import com.stylefeng.guns.common.persistence.dao.ZyTeaPictureMapper;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.page.PageBT;
import com.stylefeng.guns.core.page.PageInfoBT;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.PagingHandler;
import com.stylefeng.guns.modular.fileManage.dao.*;
import com.stylefeng.guns.modular.fileManage.enums.TeaLabelEnums;
import com.stylefeng.guns.modular.fileManage.service.IZyPictureService;
import com.stylefeng.guns.modular.fileManage.service.impl.QrCodeServiceImpl;

import com.stylefeng.guns.modular.fileManage.service.impl.ZyBrewsServiceImpl;
import com.stylefeng.guns.modular.fileManage.service.impl.ZyPictureServiceImpl;
import com.stylefeng.guns.modular.fileManage.warpper.PictureWarpper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.fileManage.service.IZyTeaService;


import java.io.*;

import java.nio.charset.Charset;
import java.util.*;

/**
 * 茶叶档案控制器
 *
 * @author fengshuonan
 * @Date 2017-12-21 20:25:02
 */
@Controller
@RequestMapping("/teaFile")
public class TeaFileController extends BaseController {

    private Logger log = LoggerFactory.getLogger(TeaFileController.class);

    private String PREFIX = "/fileManage/teaFile/";
    private String TABLE_NAME = "zy_tea";

    @Value("${guns.front-view-url}")
    private String url;

    @Value("${guns.domain-name}")
    private String domainName;

    @Value("${guns.qa-code-path}")
    private String qaCodePath;

    @Value("${server.context-path}")
    private String contextPath;

    @Autowired
    private IZyTeaService teaFileService;

    @Autowired
    private IZyPictureService iZyPictureService;

    @Autowired
    private ZyTeaDao zyTeaDao;

    @Autowired
    private ZyTeaMapper teaMapper;

    @Autowired
    private ZyPictureMapper pictureMapper;

    @Autowired
    private QrCodeServiceImpl qrCodeServiceImpl;

    @Autowired
    private ZyBrewsServiceImpl zyBrewsService;

    @Autowired
    private ZyRecycleDao zyRecycle;

    @Autowired
    private ZyBrewsDao zyBrewsDao;

    @Autowired
    private ZyTeaPictureDao teaPictureDao;

    @Autowired
    private ZyBrewsPictureDao brewsPictureDao;

    @Autowired
    private ZyPictureServiceImpl pictureService;

    @Autowired
    private ZyPictureDao pictureDao;

    /**
     * 跳转到茶叶档案首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "teaFile.html";
    }

    /**
     * 跳转到添加茶叶档案
     */
    @RequestMapping("/teaFile_add")
    public String teaFileAdd(Model model) {
        List<ZyBrews> list = zyBrewsDao.selectAll();
        model.addAttribute("brewsList", list);
        return PREFIX + "teaFile_add.html";
    }


    /**
     * 跳转到添加编辑详情
     */
    @RequestMapping("/teaFile_edit/{teaFileId}")
    public String editDetail(@PathVariable Integer teaFileId, Model model) {
        ZyTea teaFile = teaFileService.selectById(teaFileId);
        model.addAttribute("item", teaFile);
        LogObjectHolder.me().set(teaFile);
        return PREFIX + "teaFile_detail.html";
    }

    /**
     * 跳转到修改茶叶档案
     */
    @RequestMapping("/teaFile_update/{teaFileId}")
    public String teaFileUpdate(@PathVariable Integer teaFileId, Model model) {
        ZyTea teaFile = teaFileService.selectById(teaFileId);
        model.addAttribute("tea", teaFile);
        //获取所有冲泡方式
        List<ZyBrews> list = zyBrewsDao.selectAll();
        model.addAttribute("brewsList", list);
        LogObjectHolder.me().set(teaFile);
        //查找茶叶对应的图片
        List<ZyTeaPicture> teaPictures = teaPictureDao.selectByTeaId(teaFile.getId());
        for (int i = 0,j = 0; i < teaPictures.size(); i++) {
            Integer pictureId = teaPictures.get(i).getPictureId();
            ZyPicture picture = pictureDao.selectByPictureId(pictureId);
            PictureWarpper picWar = new PictureWarpper(picture,teaPictures.get(i),teaPictureDao);
            Map<String, Object> pictureMap = (Map<String, Object>) super.warpObject(picWar);
            if(pictureMap.get("label").equals(TeaLabelEnums.TEA.getLabel())){
                j = 0;
            }else if(pictureMap.get("label").equals(TeaLabelEnums.BRAND.getLabel())){
                j = 5;
            }else if(pictureMap.get("label").equals(TeaLabelEnums.PACKING.getLabel())){
                j = 10;
            }
            model.addAttribute("pictureMap" + (teaPictures.get(i).getSequence() + 1 + j), pictureMap);
        }
        return PREFIX + "teaFile_edit.html";
    }

    /**
     * 获取茶叶档案列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public PageInfoBT list(PageBT pageParam) {
        //使用分页查询类
        return PagingHandler.getPageResult("zy_tea", pageParam);
    }

    /**
     * 新增茶叶档案
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(ZyTea teaFile) throws Exception {
        //查询茶叶的名称是否已经存在
        List<ZyTea> teaList = zyTeaDao.selectByName(teaFile.getName());
        if (teaList != null && teaList.size() > 0) {
            throw new BussinessException(BizExceptionEnum.TEA_NAME_IS_EXIST);
        }

        //新增默认启用 设置为
        teaFile.setStatus("1");
        teaFile.setCrtTime(new Date());
        teaFile.setCrtUser(ShiroKit.getUser().getId());
        teaFile.setUpdateDate(new Date());
        teaFileService.insert(teaFile);
        String teaId = teaFile.getId().toString();
        qrCodeServiceImpl.createCode(url, teaId, teaFile.getName());
        return teaFile;
    }

    /**
     * 打开图片选择页面
     */
    @RequestMapping("/tea_picture")
    public String teaPicture(Model model, PageBT pageParam, @RequestParam("teaId") Integer teaId, @RequestParam("label") String label) {
        List<ZyPicture> resultPictures = new ArrayList<>();
        List<Integer> picIds = new ArrayList<>();
        //查询出图片(offset和limit置为空则查询表的所有记录)
        PageInfoBT pageInfo = new PageInfoBT(new Page());
        if (teaId == null) {
            //新增界面
            pageInfo = PagingHandler.getPageResult("zy_picture", pageParam);
            resultPictures = pageInfo.getRows();
            model.addAttribute("openType", "teaAdd");
        } else {
            //编辑页面
            pageInfo = PagingHandler.getPageResultByTea(pageParam, teaId, label);
            List<ZyTeaPicture> originalZtp = teaPictureDao.selectByTeaIdAndLabel(teaId, label);
            for (int i = 0; i < originalZtp.size(); i++) {
                //将图片id包装isChecked=true
                picIds.add(originalZtp.get(i).getPictureId());
            }
            resultPictures = pageInfo.getRows();
            ZyTea teaIteam = teaMapper.selectById(teaId);
            if (teaIteam == null) {
                teaIteam = new ZyTea();
                teaIteam.setName("新增冲泡方式");
            }
            model.addAttribute("teaIteam", teaIteam);
            model.addAttribute("openType", "teaEdit");
        }
        model.addAttribute("label", label);
        PictureWarpper picWar = new PictureWarpper(resultPictures, picIds);
        pageInfo.setRows((List) super.warpObject(picWar));

        model.addAttribute("pageInfo", pageInfo);
        return "/fileManage/picture/picture_Selector.html";
    }

    /**
     * 关联冲泡方式和图片
     */
    @RequestMapping("/selector")
    @ResponseBody
    public Object selector(ZyTeaPicture zyTeaPictures) {
        pictureService.selectorPictureByTea(zyTeaPictures);
        return SUCCESS_TIP;
    }

    /**
     * 关联冲泡方式和图片
     */
    @RequestMapping("/selector2")
    @ResponseBody
    public Object selector2(ZyTeaPicture zyTeaPictures) {
        System.out.println(zyTeaPictures);
        return SUCCESS_TIP;
    }

    /**
     * 删除茶叶档案
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer teaFileId, @RequestParam String teaName) {
        //更新删除状态
        zyTeaDao.delete(teaFileId);
        //用户删除成功后添加到回收站
        ZyRecycle item = new ZyRecycle();
        item.setId(teaFileId);
        item.setKeyName("name");
        item.setKeyValue(teaName);
        item.setTableName("zy_tea");
        item.setCrtUser(ShiroKit.getUser().getAccount());
        item.setCrtTime(new Date());
        zyRecycle.addRecycle(item);

        return SUCCESS_TIP;
    }

    /**
     * 修改茶叶档案
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(ZyTea teaFile) {
        //设置更新时间
        teaFile.setUpdateDate(new Date());
        teaFileService.updateById(teaFile);
        return super.SUCCESS_TIP;
    }

    /**
     * 修改茶叶详细情况
     */
    @RequestMapping(value = "/editDetail")
    @ResponseBody
    public Object editDetail(ZyTea teaFile) {
        teaFile.setUpdateDate(new Date());
        zyTeaDao.updateDetailById(teaFile);
        return super.SUCCESS_TIP;
    }

    /**
     * 茶叶档案详情
     */
    @RequestMapping(value = "/detail/{teaFileId}")
    @ResponseBody
    public Object detail(@PathVariable("teaFileId") Integer teaFileId) {
        return teaFileService.selectById(teaFileId);
    }

    /**
     * 跳转茶叶前台介绍页面
     */
    @RequestMapping(value = "/showDetail")
    public String showDetail(@RequestParam("id") Integer teaFileId, Model model) {
        ZyTea teaItem = teaFileService.selectById(teaFileId);
        //如果无茶叶信息或者茶叶状态字段（status）不为1时进入错误页面
        if (teaItem == null || !"1".equals(teaItem.getStatus())) {
            return "/404.html";
        }
        ZyBrews zyBrews = zyBrewsService.findOneByTeaId(teaFileId);
        //查询茶叶图片
        for(int i = 0;i < 15;i++){
            if(i < 5){
                List<ZyPicture> pictures1 = teaPictureDao.selectByTeaIdAndLabelAndSequence(teaFileId,TeaLabelEnums.TEA.getLabel(),i);
                PictureWarpper picWar = new PictureWarpper(pictures1);
                model.addAttribute("teaPictures" + i, super.warpObject(picWar));
            }else if(i < 10){
                List<ZyPicture> pictures1 = teaPictureDao.selectByTeaIdAndLabelAndSequence(teaFileId,TeaLabelEnums.BRAND.getLabel(),i - 5);
                PictureWarpper picWar = new PictureWarpper(pictures1);
                model.addAttribute("teaPictures" + i, super.warpObject(picWar));
            }else if(i < 15){
                List<ZyPicture> pictures1 = teaPictureDao.selectByTeaIdAndLabelAndSequence(teaFileId,TeaLabelEnums.PACKING.getLabel(),i - 10);
                PictureWarpper picWar = new PictureWarpper(pictures1);
                model.addAttribute("teaPictures" + i, super.warpObject(picWar));
            }
        }

        //查询冲泡方式图片
        if(zyBrews != null){
            for(int i = 0;i < 5;i++){
                List<ZyBrewsPicture> zbps = brewsPictureDao.selectByBrewsIdAndSequence(zyBrews.getId(),i);
                List<ZyPicture> pictures = new ArrayList<>();
                for(int j = 0;j < zbps.size();j++){
                    pictures.add(pictureMapper.selectById(zbps.get(j).getPictureId()));
                }
                PictureWarpper picWar = new PictureWarpper(pictures);
                model.addAttribute("brewsPictures" + i,super.warpObject(picWar));
            }
        }
        model.addAttribute("teaItem", teaItem);
        model.addAttribute("zyBrews", zyBrews);
        return "/fileManage/teaFile/frontView/index.html";
    }

    /**
     * 查看茶叶更多详情
     *
     * @return
     * @throws IOException
     */
    @RequestMapping("/showMoreDetail")
    public String showMoreDetail(@RequestParam("id")Integer teaId, Model model) {
        ZyTea teaItem = teaFileService.selectById(teaId);
        model.addAttribute("teaItem",teaItem);
        return "/fileManage/teaFile/frontView/goBack.html";
    }

    /**
     * 根据茶叶id查询对应的图片信息
     *
     * @param teaId 茶叶id
     * @return 对应图片map
     */
    @GetMapping("/findPicture")
    @ResponseBody
    public Map<String, List<ZyPicture>> findPicture(@RequestParam("teaId") Integer teaId) throws Exception {
        Map<String, List<ZyPicture>> map = new HashMap<>(16);
        log.info("【获取茶叶图片】，请求成功，teaId={}", teaId);
        List<ZyPicture> zyPictureList = iZyPictureService.selectByTeaId(teaId);
        //包装图片的src、label、sequence额外字段信息
        if (zyPictureList != null || zyPictureList.size() > 0) {
            PictureWarpper picWar = new PictureWarpper(zyPictureList, teaId, teaPictureDao);
            map.put("zyPictureList", (List<ZyPicture>) super.warpObject(picWar));
        }
        return map;
    }

    /**
     * 显示二维码
     *
     * @param teaFileId
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/QR_show/{teaFileId}")
    public String showQR(@PathVariable Integer teaFileId, Model model) throws Exception {
        ZyTea teaFile = teaFileService.selectById(teaFileId);
        String name = teaFile.getName();
        //二维码显示的地址
        String showQRUrl = contextPath +  "/static/" + qaCodePath + "/" + teaFileId.toString() + "_"  + name.toString() + ".png";
        //判断二维码是否存在 若不存在就生成一张新的二维码
        File file = new File(showQRUrl);
        if (!file.exists()) {
            //这里的url是链接到主页的二维码地址
            qrCodeServiceImpl.createCode(url, teaFileId.toString(), teaFile.getName());
        }
        model.addAttribute("name", name);
        model.addAttribute("url", showQRUrl);
        LogObjectHolder.me().set(teaFile);

        return PREFIX + "teaFile_QR.html";
    }

    /**
     * 下载二维码
     *
     * @param ids 拼接的id数组
     * @return
     * @throws Exception
     */
    @RequestMapping("/download")
    public Object downLoadList(@RequestParam("ids") String ids) throws Exception {
        //将传入的拼接id转成id数组（根据小横杠分割数组）
        String idArray[] = ids.split("-");
        List<ZyTea> list = zyTeaDao.selectByIds(idArray);
        ResponseEntity<byte[]> object = qrCodeServiceImpl.downloadList(list);
        return object;
    }

}
